/*
 * The MIT License
 *
 * Copyright (c) 2010, Seiji Sogabe
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package hudson.plugins.googlecodetrigger;

import hudson.Extension;
import hudson.Util;
import hudson.model.AbstractProject;
import hudson.model.Action;
import hudson.model.BuildableItem;
import hudson.model.Hudson;
import hudson.model.Item;
import hudson.model.Run;
import hudson.triggers.Trigger;
import hudson.triggers.TriggerDescriptor;
import hudson.util.Secret;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import org.acegisecurity.AccessDeniedException;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;

/**
 *
 * @author sogabe
 */
public class GooglecodeTrigger extends Trigger<BuildableItem> {

    private final Secret secret;

    private final boolean checkRevision;

    @DataBoundConstructor
    public GooglecodeTrigger(String key, boolean checkRevision) {
        super();
        this.secret = Secret.fromString(Util.fixEmptyAndTrim(key));
        this.checkRevision = checkRevision;
    }

    public String getKey() {
        return Secret.toString(secret);
    }

    public boolean isCheckRevision() {
        return checkRevision;
    }

    @Override
    public Collection<? extends Action> getProjectActions() {
        GooglecodeTriggerAction action = new GooglecodeTriggerAction(this);
        return Collections.singletonList(action);
    }

    public void run(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
        LOGGER.fine("run called.");
        // Check security of Hudson self if Post-Commit Authentication Key not specified.
        if (secret == null) {
            if (!hasPermission()) {
                LOGGER.info("The request has no valid permission.");
                return;
            }
        } else if (!hasValidHMAC(req)) {
            LOGGER.info("Post-Commit Authentication Key is unmatch.");
            return;
        }

        String rev = Util.fixEmptyAndTrim(req.getParameter("rev"));

        if (checkRevision && isTriggered(rev)) {
            LOGGER.info("Revision: " + rev + " has already been triggered.");
            return;
        }

        int delay = ((AbstractProject<?, ?>) job).getDelay(req);
        GooglecodeTriggerCause cause = new GooglecodeTriggerCause(req.getRemoteAddr(), rev);
        job.scheduleBuild(delay, cause);
    }

    private boolean hasPermission() {
        if (!Hudson.getInstance().isUseSecurity()) {
            LOGGER.fine("No security used.");
            return true;
        }
        try {
            ((AbstractProject<?, ?>) job).checkPermission(AbstractProject.BUILD);
        } catch (AccessDeniedException e) {
            return false;
        }
        return true;
    }

    private boolean hasValidHMAC(StaplerRequest req) {
        GooglecodeHookHMAC hmac = new GooglecodeHookHMAC(getKey());
        return hmac.validate(req);
    }

    private boolean isTriggered(String rev) {
        if (rev == null) {
            return false;
        }
        Run<?, ?> b = ((AbstractProject<?, ?>) job).getLastBuild();
        while (b != null) {
            GooglecodeTriggerCause cause = b.getCause(GooglecodeTriggerCause.class);
            if (cause != null) {
                String r = cause.getRev();
                if (rev.equals(r)) {
                    return true;
                }
            }
            b = b.getPreviousBuild();
        }
        return false;
    }

    @Extension
    public static class DescriptorImpl extends TriggerDescriptor {

        @Override
        public boolean isApplicable(Item item) {
            return item instanceof BuildableItem;
        }

        @Override
        public String getDisplayName() {
            return Messages.GooglecodeTrigger_DisplayName();
        }
    }

    private static final Logger LOGGER = Logger.getLogger(GooglecodeTrigger.class.getName());
}
